﻿@namespace AntBlazor
@using OneOf;
@inherits AntDomComponentBase

<button type="button" role="switch"
        aria-checked="@_isChecked"
        disabled="@Disabled"
        class="@ClassMapper.Class"
        style="@Style"
        @onclick="@OnClickHandler">
    @if (Loading)
    {
        <AntIcon type="loading" Class="@($"{prefixCls}-loading-icon")" />
    }
    <span class="@($"{prefixCls}-inner")">
        @if (_isChecked)
        {
            if (CheckedChildren.IsT0)
            {
                @(CheckedChildren.AsT0)
            }
            else
            {
                @(CheckedChildren.AsT1)
            }
        }
        else
        {
            if (UnCheckedChildren.IsT0)
            {
                @(UnCheckedChildren.AsT0)
            }
            else
            {
                @(UnCheckedChildren.AsT1)
            }
        }
    </span>
</button>

@code {

    protected string prefixCls = "ant-switch";

    protected override Task OnParametersSetAsync()
    {
        ClassMapper.Clear()
            .Add(prefixCls)
            .If($"{prefixCls}-checked", () => _isChecked)
            .If($"{prefixCls}-disabled", () => Disabled || Loading)
            .If($"{prefixCls}-loading", () => Loading)
            .If($"{prefixCls}-small", () => Size.Equals("small"))
            ;


        return base.OnParametersSetAsync();
    }

    private bool _isChecked = false;

    [Parameter]
    public bool Checked { get; set; }

    [Parameter]
    public bool Disabled { get; set; }

    [Parameter]
    public bool Loading { get; set; }

    [Parameter]
    public bool Control { get; set; }

    [Parameter]
    public string Size { get; set; } = "default";


    [Parameter]
    public EventCallback<bool> OnChange { get; set; }

    [Parameter]
    public OneOf<string,RenderFragment> CheckedChildren { get; set; }

    [Parameter]
    public OneOf<string,RenderFragment> UnCheckedChildren { get; set; }


    protected override void OnInitialized()
    {
        this._isChecked = Checked;
        base.OnInitialized();
    }

    protected void OnClickHandler(MouseEventArgs ev)
    {
        if (!Disabled && !Loading && !Control)
        {
            this.updateValue(!this._isChecked);
        }
    }

    private void updateValue(bool value)
    {
        if (this._isChecked != value)
        {
            this._isChecked = value;
            this.OnChange.InvokeAsync(this._isChecked);
        }
    }

}
